<?php

namespace app\common\library;

use think\Config;
use think\Db;

/**
 * 千牛用户角色管理工具类
 */
class QianniuUserRole
{
    private $config;
    
    public function __construct()
    {
        $this->config = Config::get('qianniu');
    }
    
    /**
     * 获取用户角色
     */
    public function getUserRole($userId)
    {
        // 先从数据库查询用户角色
        $userRole = Db::name('qianniu_user_role')
            ->where('user_id', $userId)
            ->where('status', 1)
            ->value('role_type');
            
        if ($userRole) {
            return $userRole;
        }
        
        // 如果数据库中没有，根据千牛用户信息判断
        $qianniuUserInfo = session('qianniu_user_info');
        if ($qianniuUserInfo) {
            return $this->determineRoleByQianniuInfo($qianniuUserInfo);
        }
        
        return 'employee'; // 默认角色
    }
    
    /**
     * 根据千牛用户信息判断角色
     */
    private function determineRoleByQianniuInfo($qianniuUserInfo)
    {
        $departments = $this->config['departments'] ?? [];
        $positions = $this->config['positions'] ?? [];
        
        // 根据部门ID判断角色
        if (isset($qianniuUserInfo['department_ids']) && is_array($qianniuUserInfo['department_ids'])) {
            foreach ($qianniuUserInfo['department_ids'] as $deptId) {
                if (isset($departments[$deptId])) {
                    return $departments[$deptId];
                }
            }
        }
        
        // 根据职位判断角色
        if (isset($qianniuUserInfo['position'])) {
            $position = $qianniuUserInfo['position'];
            foreach ($positions as $pos => $role) {
                if ($pos !== 'default' && strpos($position, $pos) !== false) {
                    return $role;
                }
            }
        }
        
        return $departments['default'] ?? $positions['default'] ?? 'employee';
    }
    
    /**
     * 检查用户权限
     */
    public function checkPermission($userId, $permission)
    {
        $userRole = $this->getUserRole($userId);
        $roles = $this->config['roles'] ?? [];
        
        if (!isset($roles[$userRole])) {
            return false;
        }
        
        $permissions = $roles[$userRole]['permissions'] ?? [];
        return in_array($permission, $permissions);
    }
    
    /**
     * 获取用户所有权限
     */
    public function getUserPermissions($userId)
    {
        $userRole = $this->getUserRole($userId);
        $roles = $this->config['roles'] ?? [];
        
        if (!isset($roles[$userRole])) {
            return [];
        }
        
        return $roles[$userRole]['permissions'] ?? [];
    }
    
    /**
     * 设置用户角色
     */
    public function setUserRole($userId, $qianniuUserId, $corpId, $roleType, $deptIds = [], $permissions = [])
    {
        $data = [
            'user_id' => $userId,
            'qianniu_user_id' => $qianniuUserId,
            'corp_id' => $corpId,
            'role_type' => $roleType,
            'dept_ids' => json_encode($deptIds),
            'permissions' => json_encode($permissions),
            'status' => 1,
            'createtime' => time(),
            'updatetime' => time()
        ];
        
        // 检查是否已存在
        $exists = Db::name('qianniu_user_role')
            ->where('qianniu_user_id', $qianniuUserId)
            ->find();
            
        if ($exists) {
            // 更新
            return Db::name('qianniu_user_role')
                ->where('qianniu_user_id', $qianniuUserId)
                ->update($data);
        } else {
            // 新增
            return Db::name('qianniu_user_role')->insert($data);
        }
    }
    
    /**
     * 同步千牛组织架构
     */
    public function syncQianniuOrganizations($corpId, $organizations)
    {
        foreach ($organizations as $org) {
            $data = [
                'corp_id' => $corpId,
                'dept_id' => $org['dept_id'],
                'dept_name' => $org['dept_name'],
                'parent_id' => $org['parent_id'] ?? 0,
                'level' => $org['level'] ?? 1,
                'status' => 1,
                'createtime' => time(),
                'updatetime' => time()
            ];
            
            // 检查是否已存在
            $exists = Db::name('qianniu_organization')
                ->where('corp_id', $corpId)
                ->where('dept_id', $org['dept_id'])
                ->find();
                
            if ($exists) {
                // 更新
                Db::name('qianniu_organization')
                    ->where('corp_id', $corpId)
                    ->where('dept_id', $org['dept_id'])
                    ->update($data);
            } else {
                // 新增
                Db::name('qianniu_organization')->insert($data);
            }
        }
        
        return true;
    }
    
    /**
     * 获取组织架构
     */
    public function getOrganizations($corpId)
    {
        return Db::name('qianniu_organization')
            ->where('corp_id', $corpId)
            ->where('status', 1)
            ->order('level, dept_id')
            ->select();
    }
    
    /**
     * 获取部门成员
     */
    public function getDepartmentMembers($corpId, $deptId)
    {
        return Db::name('user')
            ->alias('u')
            ->join('qianniu_user_role qur', 'u.id = qur.user_id')
            ->where('qur.corp_id', $corpId)
            ->where('qur.status', 1)
            ->where('u.status', 'normal')
            ->field('u.id, u.nickname, u.avatar, u.employee_no, qur.role_type')
            ->select();
    }
    
    /**
     * 根据角色获取用户列表
     */
    public function getUsersByRole($corpId, $roleType)
    {
        return Db::name('user')
            ->alias('u')
            ->join('qianniu_user_role qur', 'u.id = qur.user_id')
            ->where('qur.corp_id', $corpId)
            ->where('qur.role_type', $roleType)
            ->where('qur.status', 1)
            ->where('u.status', 'normal')
            ->field('u.id, u.nickname, u.avatar, u.employee_no')
            ->select();
    }
    
    /**
     * 获取角色列表
     */
    public function getRoleList()
    {
        $roles = $this->config['roles'] ?? [];
        $roleList = [];
        
        foreach ($roles as $key => $role) {
            $roleList[] = [
                'key' => $key,
                'name' => $role['name'],
                'permissions' => $role['permissions']
            ];
        }
        
        return $roleList;
    }
    
    /**
     * 获取权限列表
     */
    public function getPermissionList()
    {
        $permissions = [
            'order_manage' => '订单管理',
            'order_view' => '订单查看',
            'allocation_manage' => '分工管理',
            'allocation_view' => '分工查看',
            'report_audit' => '报工审核',
            'report_submit' => '报工提交',
            'report_view' => '报工查看',
            'user_manage' => '用户管理',
            'user_view' => '用户查看',
            'product_manage' => '产品管理',
            'process_manage' => '工序管理',
            'statistics_view' => '统计查看'
        ];
        
        return $permissions;
    }
}
